#!/usr/bin/env bash

# exit on error
set -e

# color the output
RED='\e[31m'
GREEN='\e[32m'
NORMAL='\e[0m'

if [ $# -lt 1 ]; then
    echo -e "${RED}ERROR: No arg provided${NORMAL}"
    exit 1
fi

arg=$1
dest_folder=""
src_pattern=""

src_format="(c|cpp|py)"

if [[ ${arg} == "leetcode" ]]; then
    src_pattern="^p[0-9]+(v[2-9])?\\.${src_format}\$"
    # NOTE: If you use tilde (~/Documents) here, mv will fail with 'No such directory' error.
    # '~' is a feature in Bash. MV and open() will NOT treat it as HOME.
    # And ${} is simple string replacement. Bash does not parse the tilde within the variable.
    dest_folder="$HOME/Documents/leetcode/"
elif [[ ${arg} == "pat" ]]; then
    src_pattern="^pat[0-9]+\\.${src_format}\$"
    dest_folder="$HOME/Documents/pat_advanced/"
else
    echo -e "${RED}ERROR: unknown arg: \`${arg}\`${NORMAL}"
    exit 1
fi

# debug
# echo ${src_pattern}
# echo ${dest_folder}

# search the pattern from all the files in the current path
files=$(grep -l -I -E "^AC 20[0-9]{6}$" -r | grep -E "${src_pattern}" | xargs echo)
echo "${files}"

# DEBUG
echo "mv ${files} -n -t ${dest_folder}"

# move files
mv ${files} -n -t "${dest_folder}"
echo -e "${GREEN}DONE${NORMAL}"
